package sample.`fun`

/**
 * Created by runjia on 17-5-25.
 */
fun buildString(builderAction: StringBuilder.() -> Unit): String {
    var sb = StringBuilder()
    sb.builderAction()
    return sb.toString()
}

fun <T> T.buildString1(builderAction: T.() -> Unit): T {
    this.apply(builderAction)   // apply, actively
    return this
}

fun buildString2(builderAction: (StringBuilder) -> Unit): String {
    var sb = StringBuilder()
    builderAction(sb)
    return sb.toString()
}

fun <T> T.buildString3(builderAction: (T) -> Unit): T {
    builderAction.invoke(this)  // invoke, passively
    return this
}

fun main(args:Array<String>) {
    val str : String = buildString {
        append("i am")
        append(" Jack")
    }
    println(str)

    val str1 : String = StringBuilder().buildString1 {
        append("i am")
        append(" Jack")
    }.toString()
    println(str1)

    val str2 : String = buildString2 {
        it.append("i am")
        it.append(" Jack")
    }
    println(str2)

    val str3 = StringBuilder().buildString3 {
        it.append("i am")
        it.append(" Jack")
    }.toString()
    println(str3)

    var data: String? = "abc"
    var result = data ?.let{ null } ?: run { "123" }
    println(result)
}
